package cn.kicsy.www.anonymous_bbs.controller;

import cn.kicsy.www.anonymous_bbs.entity.Comment;
import cn.kicsy.www.anonymous_bbs.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.ArraySchema;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@Tag(name = "评论管理", description = "评论和回复相关的API接口")
@RestController
@RequestMapping("/api")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    /**
     * 发表评论
     * @param request 评论请求
     * @param httpRequest HTTP请求，用于获取用户IP地址
     * @return 创建的评论
     */
    @Operation(summary = "发表评论", description = "为帖子发表匿名评论")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "评论成功", content = @Content(schema = @Schema(implementation = Comment.class))),
        @ApiResponse(responseCode = "400", description = "评论失败", content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
    })
    @PostMapping("/comments")
    public ResponseEntity<?> createComment(@RequestBody @Parameter(description = "评论内容请求") CommentRequest request, HttpServletRequest httpRequest) {
        try {
            String ipAddress = getClientIpAddress(httpRequest);
            Comment comment = commentService.createComment(request.getPostId(), request.getContent(), ipAddress);
            return ResponseEntity.ok(comment);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 回复评论
     * @param parentCommentId 父评论ID
     * @param request 回复请求
     * @param httpRequest HTTP请求，用于获取用户IP地址
     * @return 创建的回复
     */
    @Operation(summary = "回复评论", description = "回复其他用户的评论")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "回复成功", content = @Content(schema = @Schema(implementation = Comment.class))),
        @ApiResponse(responseCode = "400", description = "回复失败", content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
    })
    @PostMapping("/comments/{parentCommentId}/reply")
    public ResponseEntity<?> replyToComment(@PathVariable @Parameter(description = "父评论ID") Long parentCommentId, 
                                          @RequestBody @Parameter(description = "回复内容请求") ReplyRequest request, 
                                          HttpServletRequest httpRequest) {
        try {
            String ipAddress = getClientIpAddress(httpRequest);
            Comment reply = commentService.replyToComment(request.getPostId(), parentCommentId, request.getContent(), ipAddress);
            return ResponseEntity.ok(reply);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取帖子的根评论列表
     * @param postId 帖子ID
     * @return 根评论列表，按创建时间升序排列
     */
    @Operation(summary = "获取帖子评论列表", description = "获取指定帖子的所有根评论")
    @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Comment.class))))
    @GetMapping("/posts/{postId}/comments")
    public List<Comment> getPostComments(@PathVariable @Parameter(description = "帖子ID") Long postId) {
        return commentService.getRootCommentsByPostId(postId);
    }
    
    /**
     * 获取评论的回复列表
     * @param commentId 评论ID
     * @return 回复列表，按创建时间升序排列
     */
    @Operation(summary = "获取评论回复列表", description = "获取指定评论的所有回复")
    @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Comment.class))))
    @GetMapping("/comments/{commentId}/replies")
    public List<Comment> getCommentReplies(@PathVariable @Parameter(description = "评论ID") Long commentId) {
        return commentService.getRepliesByCommentId(commentId);
    }
    
    /**
     * 点赞评论
     * @param commentId 评论ID
     * @param request HTTP请求，用于获取用户IP地址
     * @return 点赞后的点赞数
     */
    @Operation(summary = "点赞评论", description = "为评论点赞")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "点赞成功", content = @Content(schema = @Schema(implementation = LikeResponse.class))),
        @ApiResponse(responseCode = "400", description = "点赞失败", content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
    })
    @PostMapping("/comments/{commentId}/like")
    public ResponseEntity<?> likeComment(@PathVariable @Parameter(description = "评论ID") Long commentId, HttpServletRequest request) {
        try {
            String ipAddress = getClientIpAddress(request);
            int likeCount = commentService.likeComment(commentId, ipAddress);
            return ResponseEntity.ok(new LikeResponse(likeCount));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取客户端IP地址
     * @param request HTTP请求
     * @return 客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 如果是多个IP地址，取第一个（通常是真实IP）
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
    
    // 请求和响应模型类
    @Schema(description = "评论请求")
    public static class CommentRequest {
        private Long postId;
        private String content;
        
        public Long getPostId() {
            return postId;
        }
        
        public void setPostId(Long postId) {
            this.postId = postId;
        }
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }
    
    @Schema(description = "回复请求")
    public static class ReplyRequest {
        private Long postId;
        private String content;
        
        public Long getPostId() {
            return postId;
        }
        
        public void setPostId(Long postId) {
            this.postId = postId;
        }
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }
    
    @Schema(description = "点赞响应")
    public static class LikeResponse {
        private int likeCount;
        
        public LikeResponse(int likeCount) {
            this.likeCount = likeCount;
        }
        
        public int getLikeCount() {
            return likeCount;
        }
        
        public void setLikeCount(int likeCount) {
            this.likeCount = likeCount;
        }
    }
    
    @Schema(description = "错误响应")
    public static class ErrorResponse {
        private String message;
        
        public ErrorResponse(String message) {
            this.message = message;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
    }
}